import { readFileSync, readdirSync } from 'fs'

const attributeMatch = {
  svgTag: /<svg([^>+].*?)>/,
  clearWidthHeight: /(width|height)="([^>+].*?)"/g,
  hasViewBox: /(viewBox="[^>+].*?")/g,
  clearReturn: /(\r)|(\n)/g
}
let idPerfix = ''

function recursivelyFindSvg(dir) {
  const svgRes = []
  const dirents = readdirSync(dir, {
    withFileTypes: true
  })
  for (const dirent of dirents) {
    if (dirent.isDirectory()) {
      svgRes.push(...recursivelyFindSvg(dir + dirent.name + '/'))
    } else {
      const svg = readFileSync(dir + dirent.name)
        .toString()
        .replace(attributeMatch.clearReturn, '')
        .replace(attributeMatch.svgTag, ($1, $2) => {
          let width = 0
          let height = 0
          let conts = $2.replace(attributeMatch.clearWidthHeight, (s1, s2, s3) => {
            if (s2 === 'width') {
              width = s3
            } else if (s2 === 'height') {
              height = s3
            }
            return ''
          })
          if (!attributeMatch.hasViewBox.test($2)) {
            conts += `viewBox="0 0 ${width} ${height}"`
          }
          return `<symbol id="${idPerfix}-${dirent.name.replace('.svg', '')}" ${conts}>`
        })
        .replace('</svg>', '</symbol>')
      svgRes.push(svg)
    }
  }
  return svgRes
}

export const svgTagView = (path, perfix = 'icon') => {
  if (path === '') return
  idPerfix = perfix
  const res = recursivelyFindSvg(path)
  return {
    name: 'svg-transform',
    transformIndexHtml(html) {
      return html.replace('<body>', `<body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">${res.join('')}</svg>`)
    }
  }
}